package com.cvic.se.service.impl;

import com.cvic.se.service.InstitutionService;
import com.cvic.se.utils.GenerateId;
import com.cvic.se.utils.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cvic.se.entity.Institution;
import com.cvic.se.mapper.InstitutionMapper;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * InnoDB free: 4096 kB 服务实现类
 * </p>
 *
 * @author zgx
 * @since 2021-07-21
 */
@Service
public class InstitutionServiceImpl extends ServiceImpl<InstitutionMapper, Institution> implements InstitutionService {

	@Autowired
	InstitutionMapper institutionMapper;
	
	@Override
	public Result getAllInst(){
		QueryWrapper<Institution> wrapper = new QueryWrapper<>();
		List<Institution> list = institutionMapper.selectList(wrapper);
		if(!list.isEmpty()) {
			return Result.success().data("content", list);
		}
		return Result.error();
	}
	
	@Override
	public Result getByInstId(String id) {
		QueryWrapper<Institution> wrapper = new QueryWrapper<>();
		wrapper.eq("INST_ID", id);
		
		Institution institution = institutionMapper.selectOne(wrapper);
		if(institution!=null) {
			return Result.success().data("content", institution);
		}
		return Result.error();
	}
	
	@Override
	public Result insertInst(Institution inst) {
		int temp = institutionMapper.insert(inst);
		
		if(temp==1) {
			return Result.success();
		}
		
		return Result.error();
	}
	
	@Override
	public Result deleteInst(String id) {
		int temp = institutionMapper.deleteById(id);
		
		if(temp == 1) {
			return Result.success();
		}
		return Result.error();
	}
	
	@Override
	public Result updateInst(Institution inst) {
		UpdateWrapper<Institution> wrapper = new UpdateWrapper<>();
		wrapper.eq("INST_ID", inst.getInstId());
		
		int temp = institutionMapper.update(inst, wrapper);
		if(temp == 1) {
			return Result.success();
		}
		return Result.error();
	}
	
	@Override
	public String generateCode() {
		String prefix = "ZJ";
        //获取最大编号
        List<Map<String,Object>> list = institutionMapper.getMax();
		
		String commentCode = "";
		String maxCode = "";
        //返回的list内有数据，取出list中的第一个数据
		if (!list.isEmpty()) {
			maxCode = (String) list.get(0).get("max_code");
		}
		
		if(maxCode!=null && maxCode.contains(prefix)) {
            //取maxCode中的后8位字符
			String suffix = maxCode.substring(2,10);
            //转化为数字，并加1
			int sufNum = Integer.parseInt(suffix);
			int tmpNum = sufNum + 1;
            //字符串拼接
			commentCode = prefix + GenerateId.subStr(tmpNum);
		}
		else {
			commentCode = prefix + "00000001";
		}
		
		return commentCode;
	}
}
